package cn.iocoder.yudao.module.call.controller.admin.task;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.exception.ErrorCode;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
import cn.iocoder.yudao.framework.common.util.collection.MapUtils;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder;
import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;
import cn.iocoder.yudao.module.call.controller.admin.task.vo.*;
import cn.iocoder.yudao.module.call.dal.dataobject.agent.AgentDO;
import cn.iocoder.yudao.module.call.dal.dataobject.group.GroupDO;
import cn.iocoder.yudao.module.call.dal.dataobject.task.CallTaskDO;
import cn.iocoder.yudao.module.call.dal.dataobject.voicefile.VoiceFileDO;
import cn.iocoder.yudao.module.call.mq.producer.taskcalleelistimport.TaskCalleeListImportProducer;
import cn.iocoder.yudao.module.call.service.agent.AgentService;
import cn.iocoder.yudao.module.call.service.group.GroupService;
import cn.iocoder.yudao.module.call.service.task.CallTaskService;
import cn.iocoder.yudao.module.call.service.voicefile.VoiceFileService;
import cn.iocoder.yudao.module.system.api.tenant.TenantApi;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import cn.iocoder.yudao.module.system.enums.product.ProductEnum;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;

@Tag(name = "管理后台 - 外呼任务")
@RestController
@RequestMapping("/call/task")
@Validated
public class CallTaskController {

    @Resource
    private CallTaskService taskService;

    @Resource
    private GroupService groupService;

    @Resource
    private AgentService agentService;

    @Resource
    private VoiceFileService voiceFileService;

    @Resource
    private AdminUserApi adminUserApi;

    @Resource
    private TenantApi tenantApi;

    @Resource
    private TaskCalleeListImportProducer taskCalleeListImportProducer;

    @PostMapping("/create")
    @Operation(summary = "创建外呼任务")
    @PreAuthorize("@ss.hasPermission('call:task:create')")
    public CommonResult<Long> createTask(@Valid @RequestBody CallTaskSaveReqVO createReqVO) {
        return success(taskService.createTask(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新外呼任务")
    @PreAuthorize("@ss.hasPermission('call:task:update')")
    public CommonResult<Boolean> updateTask(@Valid @RequestBody CallTaskSaveReqVO updateReqVO) {
        taskService.updateTask(updateReqVO);
        return success(true);
    }

    @PostMapping("/control")
    @Operation(summary = "控制外呼任务-启动停止")
    @PreAuthorize("@ss.hasPermission('call:task:update')")
    public CommonResult<Boolean> controlTask(@Valid @RequestBody CallTaskControlReqVO controlReqVO) {
        taskService.controlTask(controlReqVO);
        return success(true);
    }

    @GetMapping("/getIvrNum")
    @Operation(summary = "控制外呼任务-启动停止")
    public CommonResult<Integer> getIvrNum() {
        Integer ret = tenantApi.getTenantProductBalance(ProductEnum.IVR_NUM.getCode(), TenantContextHolder.getTenantId());
        return success(ret);
    }




    @DeleteMapping("/delete")
    @Operation(summary = "删除外呼任务")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('call:task:delete')")
    public CommonResult<Boolean> deleteTask(@RequestParam("id") Long id) {
        taskService.deleteTask(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得外呼任务")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('call:task:query')")
    public CommonResult<CallTaskRespVO> getTask(@RequestParam("id") Long id) {
        return success(buildTaskRespVo(taskService.getTask(id)));
    }

    private CallTaskRespVO buildTaskRespVo(CallTaskDO callTaskDO) {
        CallTaskRespVO taskRespVO = BeanUtils.toBean(callTaskDO, CallTaskRespVO.class);
        GroupDO group = groupService.getGroup(taskRespVO.getGroupId());
        if (Objects.nonNull(group)) {
            taskRespVO.setGroupName(group.getName());
            List<AgentDO> agentList = agentService.selectByGroupId(taskRespVO.getGroupId());
            if (ObjectUtil.isNotEmpty(agentList)) {
                Map<Long, AdminUserRespDTO> userMap = adminUserApi.getUserMap(convertSet(agentList, AgentDO::getOwnerUserId));
                taskRespVO.setAgentList((BeanUtils.toBean(agentList, CallTaskRespVO.agent.class, agent -> {
                    MapUtils.findAndThen(userMap, agent.getOwnerUserId(), user -> agent.setNickname(user.getNickname()));
                })));
            }
        }
        VoiceFileDO voiceFile = voiceFileService.getVoiceFileByRemoteId(Convert.toLong(taskRespVO.getAudioFile()));
        if (Objects.nonNull(voiceFile)) {
            taskRespVO.setVoiceFileName(voiceFile.getName());
            taskRespVO.setVoiceFilePath(voiceFile.getPath());
        }
        return taskRespVO;
    }

    @GetMapping("/page")
    @Operation(summary = "获得外呼任务分页")
    @PreAuthorize("@ss.hasPermission('call:task:query')")
    public CommonResult<PageResult<CallTaskRespVO>> getTaskPage(@Valid CallTaskPageReqVO pageReqVO) {
        PageResult<CallTaskDO> pageResult = taskService.getTaskPage(pageReqVO);

        return success(BeanUtils.toBean(pageResult, CallTaskRespVO.class));
    }

    @GetMapping("/simple-list")
    @Operation(summary = "获得外呼任务列表")
    @PreAuthorize("@ss.hasPermission('call:task:query')")
    public CommonResult<List<CallTaskRespVO>> getTaskList(@Valid CallTaskPageReqVO pageReqVO) {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        PageResult<CallTaskDO> pageResult = taskService.getTaskPage(pageReqVO);

        return success(BeanUtils.toBean(pageResult.getList(), CallTaskRespVO.class));
    }


    @GetMapping("/agent-simple-list")
    @Operation(summary = "获得坐席所在外呼任务列表")
    @PreAuthorize("@ss.hasPermission('call:task:query')")
    public CommonResult<List<CallTaskRespVO>> getAgentTaskList() {
        List<CallTaskDO> pageResult = taskService.getAgentTaskList();
        return success(BeanUtils.toBean(pageResult, CallTaskRespVO.class));
    }

    @GetMapping("/get-next-number")
    @Operation(summary = "获得外呼任务号码")
    @PreAuthorize("@ss.hasPermission('call:task:query')")
    @Parameter(name = "taskId")
    @Parameter(name = "mode")
    @Deprecated
    public CommonResult<CallTaskNumberRespVO> getTaskNextNumber(@RequestParam("mode") String mode, @RequestParam("taskId") Long taskId) {
        CallTaskNumberRespVO pageResult = taskService.getTaskNumber(mode, taskId);
        return success(pageResult);
    }


    @PostMapping("/recall")
    @Operation(summary = "外呼任务重呼")
    @PreAuthorize("@ss.hasPermission('call:task:create')")
    public CommonResult<Boolean> recallTask(@RequestBody CallTaskRecallReqVO reqVO) {
        taskService.recallTask(reqVO);
        return success(true);
    }

    @PostMapping("/append")
    @Operation(summary = "追加外呼号码-废弃")
    @PreAuthorize("@ss.hasPermission('call:task:create')")
    public CommonResult<Boolean> appendNumber(@RequestParam("thirdPartyTaskId") String thirdPartyTaskId, @RequestParam("number") String number) {
        taskService.appendNumber(thirdPartyTaskId, number);
        return success(true);
    }

    @PostMapping("/append-by-callee-list")
    @Operation(summary = "追加外呼号码-从呼叫名单")
    @PreAuthorize("@ss.hasPermission('call:task:create')")
    public CommonResult<Boolean> appendNumberByCalleeList(@RequestParam("thirdPartyTaskId") String thirdPartyTaskId, @RequestParam("callTaskCalleeListId") Long callTaskCalleeListId) {
        taskService.appendNumberByCalleeList(thirdPartyTaskId, callTaskCalleeListId);
        return success(true);
    }

    @PostMapping("/append-by-file")
    @OperateLog(enable = false)
    @PreAuthorize("@ss.hasPermission('call:task:create')")
    public CommonResult<Boolean> appendNumberByFile(@Valid CallTaskAppendReqVO reqVO) {
        try {
            MultipartFile file = reqVO.getFile();
            File file1 = FileUtil.createTempFile("call-task-append-files", file.getOriginalFilename(), false);
            FileUtil.writeBytes(file.getBytes(), file1.getPath());
            taskCalleeListImportProducer.sendTaskCalleeListImportMessage(file1.getPath(), null, reqVO.getThirdPartyTaskId(), reqVO.getVerify(), reqVO.getUnique());
        } catch (Exception e) {
            throw exception(new ErrorCode(100500, e.getMessage()));
        }
        return success(true);
    }

//
//    @GetMapping("/export-excel")
//    @Operation(summary = "导出外呼任务 Excel")
//    @PreAuthorize("@ss.hasPermission('call:task:export')")
//    @OperateLog(type = EXPORT)
//    public void exportTaskExcel(@Valid CallTaskPageReqVO pageReqVO,
//              HttpServletResponse response) throws IOException {
//        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
//        List<CallTaskDO> list = taskService.getTaskPage(pageReqVO).getList();
//        // 导出 Excel
//        ExcelUtils.write(response, "外呼任务.xls", "数据", CallTaskRespVO.class,
//                        BeanUtils.toBean(list, CallTaskRespVO.class));
//    }

}